<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="search">
        <el-form ref="queryFormRef" :model="queryParams" :inline="true" label-width="68px">
          <el-form-item label="批次" prop="name">
            <el-input v-model="queryParams.name" placeholder="请输入批次" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button v-hasPermi="['chicken:hatch:add']" type="primary" plain icon="Plus" @click="handleAdd">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPermi="['chicken:hatch:edit']" type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()"
              >修改</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPermi="['chicken:hatch:remove']" type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()"
              >删除</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPermi="['chicken:hatch:export']" type="warning" plain icon="Download" @click="handleExport">导出</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @query-table="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="hatchList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="批次" align="center" prop="name" />
        <el-table-column label="设备ID" align="center" prop="productName"> </el-table-column>
        <el-table-column label="经手人" align="center" prop="workerName"> </el-table-column>
        <el-table-column label="品种" align="center" prop="varietiesName"> </el-table-column>
        <el-table-column label="孵蛋数量" align="center" prop="eggNum" />
        <el-table-column label="孵蛋开始时间" align="center" prop="beginTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.beginTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="照蛋时间" align="center" prop="zhaoTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.zhaoTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="受精率" align="center" prop="fertilized" />
        <el-table-column label="喷水凉蛋时间" align="center" prop="liaTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.liaTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="落盘时间" align="center" prop="luoTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.luoTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="计划出壳时间" align="center" prop="endTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.endTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="出壳数量" align="center" prop="chickNum" />
        <el-table-column label="在养数量" align="center" prop="aliveNum" />
        <el-table-column label="出壳率" align="center" prop="chickOutRate" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button v-hasPermi="['chicken:hatch:edit']" link type="primary" icon="Edit" @click="handleUpdate(scope.row)"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button v-hasPermi="['chicken:hatch:remove']" link type="primary" icon="Delete" @click="handleDelete(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" :total="total" @pagination="getList" />
    </el-card>
    <!-- 添加或修改小鸡孵化对话框 -->
    <el-dialog v-model="dialog.visible" :title="dialog.title" width="700px" append-to-body>
      <el-form ref="hatchFormRef" :model="form" :rules="rules" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="批次" prop="name">
              <el-input v-model="form.name" placeholder="请输入批次" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="设备ID" prop="productId">
              <!-- is-single是否单选模式 -->
              <ProductsSearch
                data-text="选择设备"
                :params="{ isCustomer: true }"
                :is-single="true"
                @ok="searchPrducts($event)"
                @keyup.enter="handleQuery"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="经手人" prop="workerId">
              <el-select v-model="form.workerId" placeholder="请选择经手人">
                <el-option v-for="dict in userList" :key="dict.userId" :label="dict.nickName" :value="parseInt(dict.userId)"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="品种" prop="varietiesId">
              <el-select v-model="form.varietiesId" placeholder="请选择品种">
                <el-option v-for="item in varietiesList" :key="item.id" :label="item.name" :value="item.id"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="孵蛋数量" prop="eggNum">
              <el-input v-model="form.eggNum" placeholder="请输入孵蛋数量" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="开始日期" prop="beginTime">
              <el-date-picker v-model="form.beginTime" clearable type="date" value-format="YYYY-MM-DD HH:mm:ss" placeholder="请选择孵蛋开始时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="照蛋日期" prop="zhaoTime">
              <el-date-picker v-model="form.zhaoTime" clearable type="date" value-format="YYYY-MM-DD HH:mm:ss" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="无精蛋" prop="dieEgg">
              <el-input v-model="form.dieEgg" placeholder="请输入无精蛋数量" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="受精率" prop="fertilized">
              <el-input v-model="form.fertilized" placeholder="请输入受精率" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="凉蛋日期" prop="liaTime">
              <el-date-picker v-model="form.liaTime" clearable type="date" value-format="YYYY-MM-DD HH:mm:ss" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="落盘日期" prop="luoTime">
              <el-date-picker v-model="form.luoTime" clearable type="date" value-format="YYYY-MM-DD HH:mm:ss" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="出壳日期" prop="endTime">
              <el-date-picker v-model="form.endTime" clearable type="date" value-format="YYYY-MM-DD HH:mm:ss" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="出壳数量" prop="chickNum">
              <el-input v-model="form.chickNum" placeholder="请输入出壳数量" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="在养数量" prop="aliveNum">
              <el-input v-model="form.aliveNum" placeholder="请输入在养数量" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="出壳率" prop="chickOutRate">
              <el-input v-model="form.chickOutRate" placeholder="请输入出壳率" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="说明" prop="remark">
              <el-input v-model="form.remark" type="textarea" rows="3" placeholder="请输入内容" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Hatch" lang="ts">
import { listHatch, getHatch, delHatch, addHatch, updateHatch } from '@/api/farm/chicken/hatch';
import { HatchVO, HatchQuery, HatchForm } from '@/api/farm/chicken/hatch/types';
import { listUserByDeptId } from '@/api/system/user';
import { parseTime } from '@/utils/ruoyi';
import dayjs from 'dayjs';
import { listChickenVarieties } from '@/api/farm/chicken/chickenVarieties';
import ProductsSearch from '@/views/erp/products/search.vue';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const hatchList = ref<HatchVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const userList = ref<any>([]);
const queryFormRef = ref<ElFormInstance>();
const hatchFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: HatchForm = {
  id: undefined,
  name: undefined,
  productId: undefined,
  workerId: undefined,
  varietiesId: undefined,
  eggNum: undefined,
  beginTime: undefined,
  zhaoTime: undefined,
  dieEgg: undefined,
  fertilized: undefined,
  liaTime: undefined,
  luoTime: undefined,
  endTime: undefined,
  chickNum: undefined,
  aliveNum: undefined,
  chickOutRate: undefined,
  remark: undefined
};
const data = reactive<PageData<HatchForm, HatchQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    name: undefined,
    params: {}
  },
  rules: {
    id: [{ required: true, message: '不能为空', trigger: 'blur' }],
    name: [{ required: true, message: '批次不能为空', trigger: 'blur' }],
    productId: [{ required: true, message: '设备ID不能为空', trigger: 'change' }],
    varietiesId: [{ required: true, message: '品种不能为空', trigger: 'change' }],
    eggNum: [{ required: true, message: '孵蛋数量不能为空', trigger: 'blur' }],
    beginTime: [{ required: true, message: '孵蛋开始时间不能为空', trigger: 'blur' }]
  }
});
/*获取用户列表*/
const readUserList = async () => {
  const { data } = await listUserByDeptId(103);
  userList.value = data;
};
readUserList();
/*表单填充*/
watch(
  () => data.form.beginTime,
  (e) => {
    data.form.zhaoTime = dayjs(e).add(7, 'day').format('YYYY-MM-DD HH:mm:ss');
    console.log(dayjs(e).add(7, 'day').format('YYYY-MM-DD HH:mm:ss'));
    data.form.liaTime = dayjs(e).add(15, 'day').format('YYYY-MM-DD HH:mm:ss');
    data.form.luoTime = dayjs(e).add(18, 'day').format('YYYY-MM-DD HH:mm:ss');
    data.form.endTime = dayjs(e).add(20, 'day').format('YYYY-MM-DD HH:mm:ss');
  }
);
/*获取子组件数据*/
const searchPrducts = (vo) => {
  vo.forEach((v) => {
    form.value.productId = v.id;
    return;
  });
};
const { queryParams, form, rules } = toRefs(data);
/*获取土鸡品种列表*/
const varietiesList = ref([]);
const getChickenVarietyData = async () => {
  let res = await listChickenVarieties();
  varietiesList.value = res.rows;
};
/** 查询小鸡孵化列表 */
const getList = async () => {
  loading.value = true;
  const res = await listHatch(queryParams.value);
  hatchList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  hatchFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: HatchVO[]) => {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  getChickenVarietyData();
  dialog.visible = true;
  dialog.title = '添加小鸡孵化';
};

/** 修改按钮操作 */
const handleUpdate = async (row?: HatchVO) => {
  reset();
  getChickenVarietyData();
  const _id = row?.id || ids.value[0];
  const res = await getHatch(_id);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = '修改小鸡孵化';
};

/** 提交按钮 */
const submitForm = () => {
  hatchFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updateHatch(form.value).finally(() => (buttonLoading.value = false));
      } else {
        await addHatch(form.value).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('修改成功');
      dialog.visible = false;
      await getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: HatchVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除小鸡孵化编号为"' + _ids + '"的数据项？').finally(() => (loading.value = false));
  await delHatch(_ids);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'chicken/hatch/export',
    {
      ...queryParams.value
    },
    `hatch_${new Date().getTime()}.xlsx`
  );
};

onMounted(() => {
  getList();
});
</script>
